import logger from '../dxmodules/dxLogger.js'
import capturer from '../dxmodules/dxCapturer.js'
import center from '../dxmodules/dxEventCenter.js'
import alsa from '../dxmodules/dxAlsa.js'
import face from '../dxmodules/dxFace.js'
import dxui from '../dxmodules/dxUi.js'
import pwm from '../dxmodules/dxPwm.js'
import * as os from "os"


center.init()
alsa.init()

center.on(face.RECEIVE_MSG, faceService, "service")


let time1 = new Date().getTime()

const capturerRgbId = 'capturerRgb1'
const capturerNirId = 'capturerNir1'


// Color camera configuration parameters
let options1 = {
    id: capturerRgbId,
    path: "/dev/video3",
    width: 1280,
    height: 720,
    preview_width: 1020,
    preview_height: 600,
    preview_mode: 2,
    preview_screen_index: 0 // The order is sequential, with larger numbers appearing first.
}


// Infrared camera configuration parameters
let options2 = {
    id: capturerNirId,
    path: "/dev/video0",
    width: 800,
    height: 600,
    preview_width: 150,
    preview_height: 200,
    preview_mode: 1,
    preview_screen_index: 1 // The order is sequential, with larger numbers appearing first.
}


// Initialize the camera
capturer.worker.beforeLoop(options1)
capturer.worker.beforeLoop(options2)



// Initialize infrared fill light
pwm.request(4);
pwm.setPeriodByChannel(4, 366166)
pwm.enable(4, true);
pwm.setDutyByChannel(4, 366166 * 50 / 255)



// UI design of face border
dxui.init({ orientation: 1 }, {});
let screen_main = dxui.View.build('screen_main', dxui.Utils.LAYER.MAIN)
screen_main.scroll(false)
screen_main.bgOpa(0)
let l1 = dxui.Line.build('l1', screen_main)
l1.lineColor(0xff6600)
l1.lineWidth(8)
dxui.loadMain(screen_main)
let points




// Face module configuration parameters
let options = {
    dbPath: "/vgmj.db",
    rgbPath: "/dev/video3",
    nirPath: "/dev/video0",
    capturerRgbId: capturerRgbId,
    capturerNirId: capturerNirId,
    score: 0.61,
    mapPath: "/app/path.txt",
    // Save complete face photo path
    saveFacePath: "/app/code/resource/image/dxl1.jpg",
    // Save the path to the face thumbnail photo
    saveFaceThumbnailPath: "/app/code/resource/image/dxl2.jpg"
}

os.sleep(1000)



// Initialize the face module
face.worker.beforeLoop(options)


// 0. Face recognition mode; 1. Face registration mode
// The demo's temporary logic is first modified to register a face, then manually switched to recognition mode. The actual logic can be adjusted according to business needs.
face.setRecgMode(0)


// Modify face comparison score
options.score = 0.7
face.faceUpdateConfig(options)




while (true) {

    face.worker.loop()

    if (dxui.handler() < 0) {
        break
    }
    if (points) {
        l1.setPoints(points, points.length)
    }
    center.getEvent()
    os.sleep(10)
}






// Registration begins 2 seconds after face recognition.
let toReg = false
let toRegTime = new Date().getTime()


function faceService(data){
    switch (data.status) {
        case "track":
            if (data.rect_smooth) {
                data.rect_smooth = data.rect_smooth.map(v => parseInt(v))
                let x1 = data.rect_smooth[0]
                let y1 = data.rect_smooth[1]
                let x2 = data.rect_smooth[2]
                let y2 = data.rect_smooth[3]
                points = [[x1, y1], [x2, y1], [x2, y2], [x1, y2], [x1, y1]]
            }
            break;
        case "feature":
            let time2 = new Date().getTime()
            if (data.source == "real-time") {
                if (time2 - time1 > 5000) {
                    time1 = time2
                    // A broadcast is detected every 5 seconds.
                    alsa.ttsPlay("Face recognition")

                    if (!toReg) {
                        toReg = true
                        toRegTime = time2
                    }
                }

                if (toReg && time2 - toRegTime > 2200) {
                    // After face recognition, wait 2000ms for automatic registration; if it exceeds 2200ms, cancel registration.
                    toReg = false
                }
                if (toReg && time2 - toRegTime > 2000) {
                    let ret = face.addFaceFeatures("dxl", data);
                    if (ret) {
                        alsa.ttsPlay("Registration successful")
                    } else {
                        alsa.ttsPlay("Registration failed")
                    }

                    toReg = false
                }
            } else if (data.source == "picture") {
                logger.debug(data)
            }
            break;
        case "compare":
            alsa.ttsPlay("Successful recognition")

        default:
            logger.debug(data)
            break;
    }
}

